var scrollDefaults = {
    isHide: true,
    scrollAxis: 'xy',
    unScroll:'hidden',
    onScrollFn: undefined,
    style: {
        "radius": "6px",
        "size": "7px",
        "color": "#5DA0FF"
    }
};

function createScrollStyle(styleClzz, clazzName, style) {
    var rgb = $B.hex2RgbObj(style.color);
    var styleCtx = clazzName + '{width:' + style.size + ';height:' + style.size + '}';
    styleCtx = styleCtx + "." + styleClzz + "::-webkit-scrollbar-thumb," + "." + styleClzz + "::-webkit-scrollbar-thumb:vertical {box-shadow: inset 0 0 4px rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + ",1);border-radius:" + style.radius + ";}";
    styleCtx = styleCtx + "." + styleClzz + "::-webkit-scrollbar-thumb:hover," + "." + styleClzz + "::-webkit-scrollbar-thumb:vertical:hover{box-shadow: inset 0 0 4px rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + ",.9);background-color: " + style.color + ";}";
    $B.createHeaderStyle(styleClzz, styleCtx);
}

function getScrollYArgs(scrollTop, scrollHeight, clientHeight) {
    var heightPercentage = (clientHeight * 100 / scrollHeight);
    var vbarHeigth = clientHeight * (heightPercentage / 100);
    var vscrollSize = Math.max(clientHeight, scrollHeight) - clientHeight;
    var scrollRate = (clientHeight - vbarHeigth) / vscrollSize; 
    var posY = scrollTop * scrollRate;
    return { posY: posY, percent: heightPercentage,scrollRate:scrollRate };
}

function getScrollXArgs(scrollLeft, scrollWidth, clientWidth) {
    var widthPercentage = (clientWidth * 100 / scrollWidth);
    var vbarWidth = clientWidth * (widthPercentage / 100);
    var vscrollSize = Math.max(clientWidth, scrollWidth) - clientWidth;
    var scrollRate = (clientWidth - vbarWidth) / vscrollSize;
    var posX = scrollLeft * scrollRate;
    return { posX: posX, percent: widthPercentage,scrollRate:scrollRate };
}

function scrollAxisY(opts, $wrap) {
    var $sol = $B.DomUtils.children($wrap,".k_scrollbar_y");
    var wrap = $wrap;
    var style = opts.style;
    var scrollHeight = wrap.scrollHeight;
    var clientHeight = wrap.clientHeight;
    //console.log(clientHeight+"  "+scrollHeight);
    if (scrollHeight > (clientHeight + 2)) {
        var ret = getScrollYArgs(wrap.scrollTop, scrollHeight, clientHeight);       
        var posY = ret.posY;
        var percent = ret.percent;
        if (!$sol  || $sol.length === 0) {
            $sol = $B.DomUtils.createEl("<div class='k_scrollbar_y k_scrollbar_axis' style='cursor:pointer;position:absolute;right:0;width:" + style.size + ";border-radius:" + style.radius + ";opacity: 0.45;background:" + style.color + "'></div>");
            $B.DomUtils.append($wrap,$sol);
            if($B.draggable){
                $B.draggable($sol,{
                    nameSpace:'kscrollabr',
                    cursor:'pointer',
                    axis: 'v', // v or h  水平还是垂直方向拖动 ，默认全向
                    onDragReady:function(state){
                        $B.DomUtils.removePropData(state.target,"_scring");                      
                        return true;
                    },
                    setScrollFn:function($p){                       
                        let pel = $p.parentNode;
                        var scr = {
                            scrollLeft : $B.DomUtils.scrollLeft(pel),
                            scrollTop : $B.DomUtils.scrollTop(pel)
                        };
                        return scr;
                    },
                    onStartDrag:function(args){                   
                        var state = args.state;   
                        var $p = state.target.parentNode;   
                        var cheight =  $B.DomUtils.height($p);
                        var scrHeight = $p.scrollHeight;
                        var scrTop = $p.scrollTop;
                        var elHeight = $B.DomUtils.height(state.target);
                        var maxTop = cheight - elHeight;
                        var ret1 = getScrollYArgs(scrTop, scrHeight, cheight);
                        state.ret = ret1;
                        state.maxTop = maxTop;
                        $B.DomUtils.propData(state.target,{"_scring":"true"});
                    },
                    onDrag:function(args){
                        var state = args.state;
                        if(state._data.top < 0){
                            state._data.top = 0 ;
                        }else if(state._data.top > state.maxTop){
                            state._data.top = state.maxTop;
                        }
                        var scrollPos = state._data.top / state.ret.scrollRate;
                        $B.DomUtils.scrollTop($wrap,scrollPos);
                    },
                    onStopDrag:function(args){
                        $B.DomUtils.removePropData(args.state.target,"_scring");
                        return false;
                    },
                    onMouseUp:function(args){   
                        $B.DomUtils.removePropData(args.state.target,"_scring");
                    }
                });
            }
        }
        $B.DomUtils.css($sol,{ "height": percent + "%", "top": posY });
        $B.DomUtils.show($sol);
        $B.DomUtils.addClass($sol,"k_scrolly_show");
        $B.DomUtils.removeClass($sol,"k_scrolly_hide");          
    } else if ($sol) {
        $B.DomUtils.hide($sol);
        $B.DomUtils.addClass($sol,"k_scrolly_hide");
        $B.DomUtils.removeClass($sol,"k_scrolly_show");
    }
}
function scrollAxisX(opts, $wrap) {    
    var $sol = $B.DomUtils.children($wrap,".k_scrollbar_x");
    var wrap = $wrap;
    var style = opts.style;
    var scrollWidth = wrap.scrollWidth;
    var clientWidth = wrap.clientWidth;
    if (scrollWidth > (clientWidth + 2)) {
        var ret = getScrollXArgs(wrap.scrollLeft, scrollWidth, clientWidth);
        var posX = ret.posX;
        var percent = ret.percent;
        if (!$sol || $sol.length === 0) {
            $sol = $B.DomUtils.createEl("<div class='k_scrollbar_x k_scrollbar_axis' style='cursor:pointer;position:absolute;bottom:0;height:" + style.size + ";border-radius:" + style.radius + ";opacity: 0.45;background:" + style.color + "'></div>");
            $B.DomUtils.append($wrap,$sol);
            if($B.draggable){
                $B.draggable($sol,{
                    cursor:'pointer',
                    nameSpace:'kscrollabr',
                    axis: 'h', // v or h  水平还是垂直方向拖动 ，默认全向
                    onDragReady:function(state){
                        $B.DomUtils.removePropData(state.target,"_scring");
                        return true;
                    },
                    setScrollFn:function($p){
                        let pel = $p.parentNode;
                        var scr = {
                            scrollLeft : $B.DomUtils.scrollLeft(pel),
                            scrollTop : $B.DomUtils.scrollTop(pel)
                        };                        
                        return scr;
                    },
                    onStartDrag:function(args){
                        var state = args.state;
                        var $p = state.target.parentNode;   
                        var cwidth =   $B.DomUtils.width($p);
                        var scrWidth = $p.scrollWidth;
                        var scrLeft = $p.scrollLeft;                       
                        var ret1 = getScrollXArgs(scrLeft, scrWidth, cwidth);
                        state.ret = ret1;
                        var maxLeft = cwidth -  $B.DomUtils.width(state.target);
                        state.maxLeft = maxLeft;
                        $B.DomUtils.propData(state.target,{"_scring":"true"});
                    },
                    onDrag:function(args){
                        var state = args.state;
                        if(state._data.left < 0){
                            state._data.left = 0 ;
                        }else if(state._data.left > state.maxLeft){
                            state._data.left = state.maxLeft;
                        }
                        var scrollPos = state._data.left / state.ret.scrollRate;
                        $B.DomUtils.scrollLeft($wrap,scrollPos);
                    },
                    onStopDrag:function(args){
                        $B.DomUtils.removePropData(args.state.target,"_scring");
                        return false;
                    },
                    onMouseUp:function(args){
                        $B.DomUtils.removePropData(args.state.target,"_scring");
                    }
                });
            }        
        }
        $B.DomUtils.css($sol,{ "width": percent + "%", "left": posX });
        $B.DomUtils.show($sol);
        $B.DomUtils.addClass($sol,"k_scrollx_show");
        $B.DomUtils.removeClass($sol,"k_scrollx_hide");
    } else if ($sol.length >0) {
        $B.DomUtils.hide($sol);
        $B.DomUtils.addClass($sol,"k_scrollx_hide");
        $B.DomUtils.removeClass($sol,"k_scrollx_show");
    }
}
function myscrollbar(el,opts) {    
    opts = $B.extendObjectFn(true,{}, scrollDefaults,opts);    
    var styleClzz = "SCROLLBAR" + $B.generateMixed(5);
    var elCss = { "overflow": "hidden"};
    var scrollCss = {
        "overflow": "auto"
    };
    if (opts.scrollAxis === "x") {
        scrollCss = {
            "overflow-x": "auto",
            "overflow-y": opts.unScroll
        };
    } else if (opts.scrollAxis === "y") {
        scrollCss = {
            "overflow-x": opts.unScroll,
            "overflow-y": "auto"
        };
    }
    opts.sizeInt = parseInt(opts.style.size.replace("px", ""));
    var posAttr = $B.DomUtils.css(el,"position");
   
    if(posAttr !== "relative" && posAttr !== "absolute"){
        elCss["position"] = "relative";
    }
    $B.DomUtils.css(el,elCss);     
    var childs = $B.DomUtils.detachChilds(el);   
    var $wrapScroll = $B.DomUtils.createEl("<div class='k_scrollbar_wrap k_box_size "+styleClzz+"' style='width:100%;height:100%;'></div>");
    $B.DomUtils.append(el,$wrapScroll);
    $B.DomUtils.css($wrapScroll,scrollCss);    
    $B.DomUtils.scroll($wrapScroll,(e)=>{
        var scrollx = $B.DomUtils.scrollLeft($wrapScroll);
        var scrolly =  $B.DomUtils.scrollTop($wrapScroll);
        var $soly = $B.DomUtils.children($wrapScroll,".k_scrollbar_y");  //y轴滚动条
        var ret;     
        if ($soly.length >0 && $B.DomUtils.hasClass($soly,"k_scrolly_show") ) {
            if(!$B.DomUtils.propData($soly,"_scring")){
                let scrollHeight = $wrapScroll.scrollHeight;
                let clientHeight = $wrapScroll.clientHeight;
                ret = getScrollYArgs(scrolly, scrollHeight, clientHeight);                
                $B.DomUtils.css($soly,{ "height": ret.percent + "%", "top": ret.posY });
                $B.DomUtils.show($soly);
            }           
        }
        var $solx =  $B.DomUtils.children($wrapScroll,".k_scrollbar_x");  //x轴滚动条
        if ($solx.length >0 && $B.DomUtils.hasClass($solx,"k_scrollx_show") ) {
            if(!$B.DomUtils.propData($solx,"_scring")){
                let scrollWidth = $wrapScroll.scrollWidth;
                let clientWidth = $wrapScroll.clientWidth;
                ret = getScrollXArgs(scrollx, scrollWidth, clientWidth);              
                $B.DomUtils.css($solx,{ "width": ret.percent + "%", "left": ret.posX });
                $B.DomUtils.show($solx);
            }            
        }
        if (opts.onScrollFn) {
            opts.onScrollFn.call($wrapScroll, scrollx, scrolly);
        }
    });
    var $wrap = $B.DomUtils.createEl("<div style='position:relative;width:auto;height:auto;overflow:visible;'></div>");
    $B.DomUtils.append($wrapScroll,$wrap);   
    $B.DomUtils.append($wrap,childs);
    var clazzName = "." + styleClzz + "::-webkit-scrollbar";    
    var sclStyle =  $B.extendObjectFn(true,{}, opts.style);
    if (opts.isHide){
        sclStyle.size = '0px';
    }else{
        sclStyle.size = opts.style.size;
    }    
    sclStyle.color = "#F7F7F7"; 
    createScrollStyle(styleClzz, clazzName, sclStyle);
    $B.DomUtils.css($wrapScroll,{"scrollbar-color":"transparent transparent","scrollbar-track-color":"transparent","-ms-scrollbar-track-color": "transparent"});
    var mkScrollFn =  function (e) {
        if(opts.scrollAxis.indexOf("x") >= 0){
            scrollAxisX(opts, $wrapScroll);
        }
        if(opts.scrollAxis.indexOf("y") >= 0){
            scrollAxisY(opts, $wrapScroll);
        }   
        if(opts.onMkScrollFn){
            opts.onMkScrollFn($wrapScroll);
        }        
    };
    mkScrollFn(); 
    let b1 = $B.DomUtils.children($wrapScroll,".k_scrollbar_y");
    let b2 = $B.DomUtils.children($wrapScroll,".k_scrollbar_x");
    $B.DomUtils.addListener($wrapScroll,"myscrollabr.mouseenter",mkScrollFn );
    if (opts.isHide) {
        if(b1.length > 0){
            $B.DomUtils.hide(b1);
        }
        if(b2.length >0){
            $B.DomUtils.hide(b2);
        } 
        $B.DomUtils.addListener($wrapScroll,"myscrollabr.mouseleave", function (e) {
            var $s = this;
            var $c = $B.DomUtils.children($s,".k_scrollbar_y");
            if($c.length >0 && !$B.DomUtils.propData($c,"_scring")){                
                $B.DomUtils.hide($c);
            }            
            $c = $B.DomUtils.children($s,".k_scrollbar_x");
            if($c.length >0 && !$B.DomUtils.propData($c,"_scring")){                
                $B.DomUtils.hide($c);
            }
        });
    }
    setTimeout(function(){
        $B.DomUtils.onDomNodeChanged(function(ele,isAdd){
            let isInDom = $B.DomUtils.inDom($wrap);
            if(!isInDom){ //清理这个回调吧，
                return false;
            }            
            let isInnner = false;
            if($wrap.contains){
                isInnner = $wrap.contains(ele);
            }else{
                let pel = ele.parentNode;
                while(pel){
                    if(pel === $wrap){
                        isInnner = true;
                        break;
                    }
                    pel = pel.parentNode;
                }
            }
            if(isInnner){
                if(opts.isHide){
                    let $c = $B.DomUtils.children($wrapScroll,".k_scrollbar_y");
                    if($c.length >0 && $B.DomUtils.isHide($c)){
                        return ;
                    }
                    $c = $B.DomUtils.children($wrapScroll,".k_scrollbar_x");
                    if($c.length >0 && $B.DomUtils.isHide($c)){
                        return ;
                    }
                }
                setTimeout(()=>{
                    $B.DomUtils.trigger($wrapScroll,"myscrollabr.mouseenter");
                },20);                
            }
        });  
    },200);
    return $wrap;
}
$B["myScrollbar"] = myscrollbar; 